package cn.com.dhcc.turbo.service.monitor.gather;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.tag.CommonStaticCode.YESNO;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.consts.KernelParam;
import cn.com.dhcc.app.pub.core.util.HttpUtil;
import cn.com.dhcc.turbo.entity.monitor.Quota;
import cn.com.dhcc.turbo.entity.monitor.QuotaValueOnTime;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.service.monitor.MonitorService;
import cn.com.dhcc.turbo.service.monitor.QUOTA;
import cn.com.dhcc.turbo.service.monitor.compute.CommonCompute;
import cn.com.dhcc.turbo.service.registry.BaseInfoService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;

@Service
public class NetConnStatusGatherService {
	@SuppressWarnings("deprecation")
	Logger logger = Log.getExistLogger(LOGTYPE.MONITOR);
	@Autowired
	private NodeInfoService nodeInfoService;
	@Autowired
	private MonitorService monitorService;
	@Autowired 
	BaseInfoService baseInfoService;
	
	/**
	 * <code>
	 * 	<b>注释：</b>
	 * 	网络连接状态 true 连接成功/false 连接失败
	 * </code>
	 * <p>连接失败则不收集ftp连接状态、ftp使用率、tlq连接状态、tlq异常队列数以及tlq队列消息使用率</p>
	 * <em>***设置此属性是为了减少告警信息。***</em>
	 */
	public static boolean isConn = false;
	public static Map<String,Boolean> isNodeConnStatus= new ConcurrentHashMap<String,Boolean>();
	public static boolean getConnStatus(){
		return isConn;
	}
	
	/**
	 * 节点网络连接状态
	 */
	public boolean netConnStatus(){
		QUOTA quota = QUOTA.NET_CONN_STATUS;
		logger.info("开始收集指标["+quota.getDesc()+"]...");
		Date now = new Date();
		try {
			NodeInfo localNode = baseInfoService.getCurrentNodeInfo();
			if(localNode==null){
				logger.error("指标["+quota.getDesc()+"]值收集失败：节点未初始化...");
				return isConn;
			}
			//收集指标REGIST_SYS_NUM("regist_sys_num","注册系统数量"),
			List<NodeInfo> list = nodeInfoService.getAllLocalExchNodeList(localNode.getId());
			for (Iterator<NodeInfo> iterator = list.iterator(); iterator.hasNext();) {
				NodeInfo nodeInfo = iterator.next();
				if(localNode.getId().equals(nodeInfo.getId())) continue;
				String status = "0";
				String alertMsg = "";
				if(HttpUtil.checkUrl(nodeInfo.getInstallUrl())) {
					 //网络连通
					 status = "1";
					 isNodeConnStatus.put(nodeInfo.getNodeCode(), true);
		        }else{
		        	 isNodeConnStatus.put(nodeInfo.getNodeCode(), false);
		        }
				QuotaValueOnTime onTime = new QuotaValueOnTime();
				onTime.setCanMerge(YESNO.YES.getStatus());
				onTime.setAlertMsg(alertMsg);
				onTime.setCurrentValue1(status);
				onTime.setId(UUIDGenerator.getUUID());
				onTime.setMtime(now);
				onTime.setQuotaCode(quota.getCode());
				onTime.setOwnerId(localNode.getId()+"|"+nodeInfo.getId());
				monitorService.insertOrUpdateQuotaOnTime(onTime);
				logger.info("指标["+quota.getDesc()+"]值收集结束，值为："+status);
				//根据网络连接状态，给需要同步的指标添加默认收集值
				if("0".equals(status)){
					insertDefaultValueForSyncQuota(nodeInfo);
				}
			}
		} catch (Exception e) {
			logger.error("指标["+quota.getDesc()+"]值收集失败",e);
		}
		return isConn;
	}
	/**
	 * 网络连接异常，目的节点指标值改为默认值
	 * @param nodeInfo
	 */
	public void insertDefaultValueForSyncQuota(NodeInfo nodeInfo){
		try {
			NodeInfo localNode = baseInfoService.getCurrentNodeInfo();
			QUOTA quotas1[] ;
			int tlqEnable = KernelParam.tlqTransportPipelineEnable;
			if(tlqEnable == 1){
				quotas1 =  new QUOTA[]{ 
//						QUOTA.TONGLINGKQ_QUEUE_NUM,
						QUOTA.TONGLINGKQ_QUEUE_STATUS,
						QUOTA.FTP_FS_USED_RATE
				};
			}else{
				quotas1 =  new QUOTA[]{ 
						QUOTA.FTP_FS_USED_RATE
				};
			}
			Date now = new Date();
			 for(int i = 0 ; i < quotas1.length ; i++){
				Quota quo = monitorService.getQuotaByQuotaCode(quotas1[i].getCode());
				QuotaValueOnTime onTime = new QuotaValueOnTime();
				onTime.setCurrentValue1(CommonCompute.DEFALUT_NOT_COMPUTE_VALUE);
				onTime.setId(UUIDGenerator.getUUID());
				onTime.setMtime(now);
				onTime.setQuotaCode(quotas1[i].getCode());
				onTime.setOwnerId(nodeInfo.getId());
				monitorService.insertOrUpdateQuotaOnTime(onTime);
				logger.info("目标节点["+nodeInfo.getNodeName()+"]网络连接异常，指标["+quotas1[i].getCode()+"]值改为默认值"+quo.getDefaultValue());
			}
			 QUOTA quotas2[] ;
			 if(tlqEnable == 1){
					quotas2 =  new QUOTA[]{ 
							QUOTA.REMOTE_TONGLINGKQ_CONN_STATUS,
							QUOTA.REMOTE_FTP_CONN_STATUS,
							QUOTA.NET_CONN_STATUS
					};
				}else{
					quotas2 =  new QUOTA[]{ 
							QUOTA.REMOTE_FTP_CONN_STATUS,
							QUOTA.NET_CONN_STATUS
					};
				}
			 for(int i = 0 ; i < quotas2.length ; i++){
					Quota quo = monitorService.getQuotaByQuotaCode(quotas2[i].getCode());
					QuotaValueOnTime onTime = new QuotaValueOnTime();
					onTime.setCurrentValue1(CommonCompute.DEFALUT_NOT_COMPUTE_VALUE);
					onTime.setId(UUIDGenerator.getUUID());
					onTime.setMtime(now);
					onTime.setQuotaCode(quotas2[i].getCode());
					onTime.setOwnerId(nodeInfo.getId()+"|"+localNode.getId());
					monitorService.insertOrUpdateQuotaOnTime(onTime);
					logger.info("目标节点["+nodeInfo.getNodeName()+"]网络连接异常，指标["+quotas2[i].getCode()+"]值改为默认值"+quo.getDefaultValue());
				}
		} catch (ServiceException e) {
			logger.error(e);
		}
		
	}
}
